<script lang="ts">
export default {
    name: 'FilesUpload'
};
</script>

<script setup lang="ts">
import { ref, defineEmits, computed } from 'vue';
import { Plus, Download, Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { uploadFile as uploadRequest } from '@/api/common';
import fileIcon from '@/assets/images/file.png';

import type {
    UploadProps,
    UploadUserFile,
    UploadRawFile,
    UploadFile,
    UploadFiles,
    UploadRequestOptions
} from 'element-plus';

const props = withDefaults(
    defineProps<{
        fileList: { id: number; name: string }[];
        remark: string;
        // type: number; // 文件类型：1-图片 2-视频 3-音频 4-Word文档 5-PDF 99-其他
        limit?: number;
        disabled?: boolean;
    }>(),
    {
        fileList: () => [],
        remark: '图片',
        limit: 9,
        disabled: true
    }
);

// const fileList = ref<UploadUserFile[]>([
//     {
//         name: 'food.jpeg',
//         url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
//     }
// ]);

const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const action = import.meta.env.VITE_APP_BASE_API + '/admin/api/file/upload';
const downLoadFile = (id: number) => {
    window.open(
        import.meta.env.VITE_APP_BASE_API + `/admin/api/file/download/${id}`
    );
};
const fileList = computed(() => {
    // const result: {
    //     name: string;
    //     index: number;
    //     url?: string;
    //     id: number;
    // }[] = [];
    // props.fileList.forEach((item, index) => {
    //     if(item) {
    //         result.push({
    //             name: item?.name,
    //             index,
    //             url: `${
    //                 import.meta.env.VITE_PIC_HOST
    //             }/admin/api/file/show/image/${item?.id}`,
    //             id: item?.id as number | undefined
    //         })
    //     }

    // });
    // return props.fileList
    //     .filter(item => item)
    //     .map((item, index) => {
    //         return {

    //         };
    //     });
    // return result;
    return props.fileList.map((item, index) => {
        return {
            name: item?.name,
            index,
            url: `${import.meta.env.VITE_PIC_HOST}/admin/api/file/show/image/${
                item?.id
            }`,
            id: item?.id as number
        };
    });
});

// ['remove', 'beforeUpload', 'success']
const emits = defineEmits<{
    (
        e: 'remove',
        data: {
            uploadFile: UploadFile;
            index: number;
            uploadFiles?: UploadFiles;
        }
    ): void;
    (e: 'beforeUpload', data: UploadRawFile): void;
    (e: 'success', data: { id: number; name: string }[]): void;
}>();

const handleUpload = (rawFile: UploadRawFile) => {
    emits('beforeUpload', rawFile);
};

/**
 * 删除
 * @param uploadFile
 * @param uploadFiles
 */
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    emits('remove', {
        uploadFile,
        index: (uploadFile as any).index,
        uploadFiles
    });
};

/**
 *
 * @param uploadFile 预览
 */
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    // dialogImageUrl.value = uploadFile.url || '';
    // dialogVisible.value = true;
};

const handleSuccess = (
    response: any,
    uploadFile: UploadFile,
    uploadFiles: UploadFiles
) => {
    if (uploadFiles.every((it) => it.status == 'success')) {
        emits(
            'success',
            uploadFiles
                .filter((item) => item.response)
                .map((item) => {
                    return {
                        id: (item.response as any).data as number,
                        name: item.name
                    };
                })
        );
    }
};

const handleExceed = () => {
    ElMessage({
        type: 'error',
        message: `最多上传${props.limit}个文件`
    });
};

const handleRequest = (options: UploadRequestOptions) => {
    const rawFile = options.file;
    const arr = rawFile.name.split('.');
    const suffix = arr[arr.length - 1] || '';
    let type = 99;
    if (
        rawFile.type.indexOf('jpeg') !== -1 ||
        rawFile.type.indexOf('png') !== -1
    ) {
        type = 1;
    } else if (rawFile.type.indexOf('video') !== -1) {
        type = 2;
    } else if (['m4a', 'mp3'].includes(suffix)) {
        type = 3;
    } else if (['doc', 'docx'].includes(suffix)) {
        type = 4;
    } else if (['pdf'].includes(suffix)) {
        type = 5;
    } else {
        type = 99;
    }
    console.log(rawFile.type, rawFile.name, type);
    return uploadRequest({
        remark: options.data.remark as string,
        file: options.file,
        type
    });
};
</script>

<template>
    <div class="filesupload-container">
        <div
            class="flex-row ai-center"
            style="width: 100%"
            v-for="file in fileList"
            :key="file.id"
        >
            <div class="flex-row">
                <!-- <video ref="videoAudio" muted controls autoplay name="media" style="height:100%;width:100%">
                    <source :src="file.path" type="video/mp4">
                </video> -->
                <img :src="fileIcon" width="20" height="20" class="mr10" />
            </div>
            <div class="mr10">{{ file.name }}</div>
            <div>
                <el-button
                    style="
                        color: #4b9df5;
                        background-color: transparent;
                        border: none;
                    "
                    text
                    :icon="Download"
                    @click="() => downLoadFile(file.id)"
                    >下载</el-button
                >
            </div>
        </div>

        <el-dialog v-model="dialogVisible">
            <div>
                <img
                    style="width: 100%"
                    :src="dialogImageUrl"
                    alt="Preview Image"
                />
            </div>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.filesupload-container {
    width: 100%;
}
// :deep(.el-upload-list__item) {
//     width: 100px;
//     height: 100px;
// }
// :deep(.el-upload) {
//     width: 100px;
//     height: 100px;
// }
</style>
